package cn.timelost.hr.utils;

import cn.hutool.core.util.StrUtil;
import cn.timelost.hr.config.FileStorageConfig;
import cn.timelost.hr.config.LocalConfig;
import cn.timelost.hr.config.UpYunConfig;
import cn.timelost.hr.enums.ResultEnum;
import cn.timelost.hr.vo.ResultVo;
import com.upyun.RestManager;
import com.upyun.UpException;
import okhttp3.Response;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Random;

/**
 * @author tangjz
 */
@Component
public class FileUploadUtils {
    @Resource
    private FileStorageConfig fileStorageConfig;

    @Resource
    private LocalConfig localConfig;

    @Resource
    private UpYunConfig upYunConfig;


    public String upload(MultipartFile multipartFile) throws Exception {
        if ("local".equals(fileStorageConfig.getEngine())) {
            return localSave(multipartFile);
        } else if ("upYun".equals(fileStorageConfig.getEngine())) {
            return upYunUpload(multipartFile);
        }
        throw new RuntimeException("暂未实现的文件存储");
    }

    private String localSave(MultipartFile multipartFile) throws IOException {
        if (StrUtil.isBlank(localConfig.getPath())) {
            throw new RuntimeException("localConfig 未配置");
        }

        String fileName = "/ehr/" + genUniqueKey() + ".jpg";
        String storagePath = localConfig.getPath() + fileName;
        FileUtils.copyToFile(multipartFile.getInputStream(), new File(storagePath));
        return fileName;
    }

    private String upYunUpload(MultipartFile multipartFile) throws IOException, UpException {
        if (StrUtil.isBlank(upYunConfig.getBucketName()) || StrUtil.isBlank(upYunConfig.getUsername()) ||
                StrUtil.isBlank(upYunConfig.getPassword()) || StrUtil.isBlank(upYunConfig.getImageHost())) {
            throw new RuntimeException("upYunConfig 未配置");
        }
        RestManager manager = new RestManager(upYunConfig.getBucketName(), upYunConfig.getUsername(),
                upYunConfig.getPassword());
        String fileName = "/ehr/" + genUniqueKey() + ".jpg";
        Response response = manager.writeFile(fileName, multipartFile.getInputStream(), null);
        String imgUrl = upYunConfig.getImageHost() + fileName;
        if (response.isSuccessful()) {
            return imgUrl;
        }
        return null;
    }

    private synchronized String genUniqueKey() {
        Random random = new Random();
        Integer number = random.nextInt(900000) + 100000;
        return System.currentTimeMillis() + String.valueOf(number);
    }
}
